import { ElMessage } from 'element-plus'

export const setDocumentText = (name) => {
  document.title = name + ' - ' + __SITE_CONFIG__.siteName
}

export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

//复制
export const copyText = (text) => {
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        ElMessage.success('复制成功')
      })
      .catch((err) => {
        console.log(err)
        ElMessage.error('复制失败')
      })
  } else {
    //提示不支持复制到剪贴板
    ElMessage.warning('您的浏览器不支持复制到剪贴板，请手动复制链接')
  }
}

//获取图片地址
export function getImageUrl(name) {
  return new URL(`/public/${name}`, import.meta.url).href
}

//获取服务端文件地址
export function getStorageUrl(path) {
  if (path === undefined) {
    path = ''
  }
  //path开头是https://，直接返回
  if (path.startsWith('http')) {
    return path
  }

  const { apiUrl, storageUrl, storageProvider } = window.__SITE_CONFIG__
  let urlRoot = storageUrl || apiUrl
  if (storageProvider === 'public') {
    urlRoot += '/storage'
  }
  return urlRoot + '/' + path
}

export const xSessionId = {
  set: (id) => {
    localStorage.setItem(
      'xSessionId',
      JSON.stringify({
        id: id,
        time: new Date().getTime(),
      })
    )
  },
  get: () => {
    const xSessionIdData = localStorage.getItem('xSessionId')
    if (xSessionIdData) {
      const { id: xSessionId, time: savedTime } = JSON.parse(xSessionIdData)
      const currentTime = new Date().getTime()
      if (currentTime - savedTime > 1 * 60 * 1000) {
        localStorage.removeItem('xSessionId')
      } else {
        return xSessionId
      }
    }
    return null
  },
}
